<?php
/**
 * Created by PhpStorm.
 * User: longli
 * Date: 2020/02/25
 * Time: 15:24
 * @link http://www.lmterp.cn
 */

namespace app\common\model;

use app\common\library\Tools;
use think\Model;

abstract class BaseModel extends Model
{
    protected $isCli = false;

    /**
     * 是
     */
    const IS_YES = 1;

    /**
     * 否
     */
    const IS_NO = 0;

    public static $IS_STATUS = [
        self::IS_NO => '否',
        self::IS_YES => '是',
    ];

    protected function initialize()
    {
        parent::initialize();
        $this->isCli = Tools::isCli();
    }

    protected static function init()
    {
        static::beforeDelete(function ($data)
        {
            $tableName = static::getTable();
            if(!($data instanceof static) || $tableName == SysTrash::getTable()) return;
            // 处理数据到回收站
            $in = config('include_table');
            $out = config('exclude_table');
            if (($in == '*' || in_array($tableName, $in)) && !($out == '*' || in_array($tableName, $out)))
            {
                $pk = $data->getPk();
                $data = $data->getData();
                SysTrash::create([
                    'tablename' => $tableName,
                    'id'        => $data[$pk],
                    'data'      => serialize($data),
                ]);
            }
        });
    }

    /**
     * 过虑掉多余不需要插入的字段
     * @param array $data 需要过虑插入的数据
     * @param string|int 需要过虑掉的值
     * @date 2020/07/13
     * @author longli
     * @return array
     */
    public static function getFilterField(array $data, $filter = null)
    {
        $t = array_flip(static::getTableFields());
        if(!is_array($filter)) $filter = [$filter];
        return array_filter(array_intersect_key($data, $t), function($item)use($filter)
        {
            return $item !== null && !in_array($item, $filter, true);
        });
    }

}